import 'package:vdrag_saas/bus.dart';
import 'package:vdrag_saas/detail/http.dart';
import 'package:vdrag_saas/model/item_model.dart';

class Api {
  static Future<List<ItemModel>> listProduct(String keyword, String type, [List<String>? filters,]) async {
    String sortField = 'order:asc';
    if (Global.sortId == 2) {
      sortField = 'view_count:desc';
    }
    if (Global.sortId == 3) {
      sortField = 'like_count:desc';
    }
    String formatType = type;
    if (type == '全部') {
      formatType = '';
    }
    String params = Api.buildFilters(filters ?? [], keyword, formatType);
    String url = '/api/products?populate=*&$params&sort=$sortField&name';
    var response = await Http().get(url);
    List<ItemModel> productList = [];
    List<Map<String, dynamic>> data =
        List<Map<String, dynamic>>.from(response['data']);
    for (var row in data) {
      ItemModel item = ItemModel.fromJson(row);
      productList.add(item);
    }
    return productList;
  }
  static Future<List<String>> listTypes() async{
    var response = await Http().get('/api/types?sort=order');
    List<Map<String, dynamic>> data =List<Map<String, dynamic>>.from(response['data']);
    List<String> types = [];
    for (var row in data) {
      types.add(row['attributes']['name']);
    }
    return types;
  }

  static updateViewCount(int id, int count) {
    String url = '/api/products/$id';
    Http().put(url, data: {
      "data": {'view_count': count}
    });
  }

  static updateLikeCount(int id, int count) {
    String url = '/api/products/$id';
    Http().put(url, data: {
      "data": {'like_count': count}
    });
  }

  static String buildFilters(List<String> filters, String keyword, String type) {
    String str = '';
    int i = 0;
    for (var filter in filters) {
      str += 'filters[\$and][$i][tags][name][\$contains]=$filter&';
      i++;
    }
    str += 'filters[\$and][$i][name][\$contains]=$keyword';
    str += '&filters[\$and][${i + 1}][types][name][\$contains]=$type';
    return str;
  }
}
